import json
import threading
import tkinter as tk
from tkinter import ttk
import requests
import time

# 定义请求头
headers = {
    "Host": "trade-api.retail.mi.com",
    "dtoken": "",  # 需要替换为实际值
    "Referer": "https://trade-api.retail.mi.com",
    "x-mishop-app-source": "front-RN",
    "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 17_6_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148",
    "d-id": "",  # 需要替换为实际值
    "x-user-agent": "channel/mishop platform/mishop.ios",
    "Cookie": "serviceToken=ul9U6dihmrbIAEturVJZAnfBoVzU/3C0PCtuIGNYfsulyeQqG0Upl9NOrZJNnkA40BrkHontDW9CVYDfTqDWngn2ritVKrq3mSse0Szmqir2EeEtls9lmjrt5hcprh8mS4mzvEAw2VkgTcbZSgZvx66eK+jPpZbCIMpGHljp3ngPTVka/SaYAW+FF+/3UcbvwiEMkaFSgxZ8+IFiKZkdXOicZowTJX4O4XY7yr+gU3ei/xuavxFERwvKHyS/CO6P; xmUuid=XMGUEST-2B418191-D831-4F34-B43E-ED470E0AE49A; userId=2534386978; client_id=180100031058; masid=20029.00001; xmuuid=XMGUEST-C1F52E50-9165-11EF-938A-2FE9A6B79197; mstuid=1729617988051_643",
    "ai-recommend-status": "1",
    "mishop-model": "iPhone14,3",
    "magic-device-id": "20241023012606b691387bd1858b3a68d0803ab0b1c2d900000519cbfcf505",
    "locale": "CN",
    "baggage": "sentry-environment=RELEASE,sentry-public_key=ee0a98b8e8e3417c89db4f9fd258ef62,sentry-release=com.xiaomi.mishop%405.2.234%2B2024101401,sentry-sample_rate=1,sentry-trace_id=56ee34f80f1c468787ba90fef5c09322,sentry-transaction=MSNewMainViewController",
    "mishop-client-id": "180100031055",
    "device-id": "1035E8F7A1EE9AAEF073D87279EC437D",
    "network-carrier": "6553565535",
    "ios-version": "system=17.6.1&device=iPhone14,3",
    "ios-app-version": "5.2.234",
    "mishop-channel-id": "",
    "Accept-Language": "zh-CN,zh-Hans;q=0.9",
    "device-oaid": "JMFuSOw+S4xfF9hbLihBp9xvCgfroWWqVqWysUpQ+mNs0t6I0jx991cIgUcb0BS/",
    "Accept": "*/*",
    "Content-Type": "application/json",
    "mishop-client-versioncode": "5.2.234",
    "sentry-trace": "56ee34f80f1c468787ba90fef5c09322-8025b800c29b49fe-1",
    "d-model": "aVBob25lMTQsMw=="
}
# 接口地址
ADD_CART = 'https://trade-api.retail.mi.com/mtop/b2csvr/cart/add'
CHK_ORDER = 'https://trade-api.retail.mi.com/mtop/b2csvr/order/checkout'
SUB_ORDER = 'https://trade-api.retail.mi.com/mtop/b2csvr/order/submit'

# 添加商品到购物车的函数
def add_to_cart(session):

    # 这里需要根据API的要求设置正确的参数
    payload = [{}, {
        "products": [{
            "ssuId": "2193600008",
            # "ssuId": "2230002053",
            "consumption": "1",
            "source": "common",
            "token": "",
            "shipmentType": "depot"
        }],
        "quickOrder": "1"
    }]
    payload = json.dumps(payload)

    response = session.post(ADD_CART, headers=headers, data=payload, verify=False)
    print('返回参数')
    print(response)
    # 检查响应状态码
    if response.status_code == 200:
        try:
            # 尝试将响应内容解析为JSON
            response_data = response.json()
            # 打印整个JSON对象
            print(response_data)

            # 如果您知道JSON的结构，可以直接访问特定的键
            # 例如，假设返回的JSON有一个名为'result'的键
            data = response_data.get('data', {})
            print('msg:', data['result'][0]['msg'])
            if data['result'][0]['msg'] == "添加成功":
                return True,data

        except ValueError:
            # 如果响应内容不是JSON格式，打印原始文本
            return False,[]
    else:
        print(f'请求失败，状态码：{response.status_code}')
        print(response.text)
        return False,[]

# 校验订单的函数
def check_order(session):

    # 这里需要根据API的要求设置正确的参数
    payload = [{}, {
        "cartType": 1,
        "addressId": "11000000173792824",
        "couponId": "0",
        "userCardId": "",
        "couponType": "2",
        "useShoppingCoupon": True,
        "ecard": "",
        "useRedpacket": 1,
        "extend": {},
        "usePurchaseSubsidy": True
    }]
    payload = json.dumps(payload)

    response = session.post(CHK_ORDER, headers=headers, data=payload, verify=False)
    print('返回参数 - 校验购物车')
    print(response)
    # 这里也需要根据API的要求设置正确的参数
    # 检查响应状态码
    if response.status_code == 200:
        try:
            # 尝试将响应内容解析为JSON
            response_data = response.json()
            # 打印整个JSON对象
            print(response_data)
            # 如果您知道JSON的结构，可以直接访问特定的键
            # 例如，假设返回的JSON有一个名为'result'的键
            data = response_data.get('data', {})
            print('data:', data)
            print('totalPrice:',data['totalPrice'] )
            if data['usableCoupons'][0]['couponId'] != 0:
                print('couponId:', data['usableCoupons'][0]['couponId'])
                return True, data['totalPrice'],data['usableCoupons'][0]['couponId']
            elif data['unusableCoupons'][0]['couponId'] != 0:
                print('couponId:', data['unusableCoupons'][0]['couponId'])
                return True, data['totalPrice'],data['unusableCoupons'][0]['couponId']
            else:
                return False, '',''
        except ValueError:
            # 如果响应内容不是JSON格式，打印原始文本
            return False, '', ''
    else:
        print(f'请求失败，状态码：{response.status_code}')
        print(response.text)
        return False, '', ''


# 提交订单的函数
def submit_order(session, price, couponId):
    # 这里需要根据API的要求设置正确的参数
    payload = [{}, {
        "cartType": "1",
        "addressId": "11000000173792824",
        "couponId": str(couponId),
        "invoiceDescrs": {
            "-1": {
                "descr": "",
                "invoiceType": 15,
                "invoiceCompanyCode": "",
                "invoiceTitle": "个人",
                "invoiceEmail": "",
                "invoiceTel": "150****6301",
                "invoiceBank": "",
                "invoiceBankCode": "",
                "invoiceCompanyTel": "",
                "invoiceCompanyAddress": ""
            }
        },
        "checkoutPrice": str(price),
        "couponType": "2",
        "useShoppingCoupon": True,
        "ecard": "",
        "ecardVcode": "",
        "expectDeliveryTime": "{\"cant_change\":[{\"timeStamp\":1729872000,\"orgCode\":\"\",\"checked\":false,\"desc\":\"中小件预计10月26日送达\"}]}",
        "extendField": "{}",
        "usePurchaseSubsidy": True,
        "useRedpacket": -1
    }]
    payload = json.dumps(payload)
    print('入参')
    print(payload)

    response = session.post(SUB_ORDER, headers=headers, data=payload, verify=False)
    print('返回参数 - 下单')
    print(response)
    # 这里也需要根据API的要求设置正确的参数
    # 检查响应状态码
    if response.status_code == 200:
        try:
            # 尝试将响应内容解析为JSON
            response_data = response.json()
            # 打印整个JSON对象
            print(response_data)
            # 如果您知道JSON的结构，可以直接访问特定的键
            # 例如，假设返回的JSON有一个名为'result'的键
            data = response_data.get('data', {})
            return data

        except ValueError:
            # 如果响应内容不是JSON格式，打印原始文本
            return response
    else:
        print(f'请求失败，状态码：{response.status_code}')
        print(response.text)
        return response


# 调用API的函数
def call_api(num):
    with requests.Session() as session:
        # 添加商品到购物车
        add_car_bool, add_response = add_to_cart(session)

        list_box.insert(tk.END, f"1 - 添加购物车成功: {add_response}")

        if add_car_bool == True:
            # 校验订单
            check_bool,price,couponId = check_order(session)
            list_box.insert(tk.END, f"Check Order: {couponId }")

            if check_bool == True:
                # 提交订单
                submit_response = submit_order(session, price, couponId)
                list_box.insert(tk.END, f"Submit Order: {submit_response}")
        else :
            list_box.insert(tk.END, f"添加购物车失败: {add_response}")


def start_task():
    is_running.set(True)
    threading.Thread(target=run_schedule).start()

def run_schedule():
    num = 0
    # while is_running.get():
    #     num += 1
    #     call_api(num)
    #     time.sleep(3)  # 每隔3秒调用一次API
    call_api(num)


def stop_task():
    is_running.set(False)

# 创建主窗口
root = tk.Tk()
root.title("定时任务控制")

# 创建列表框
list_box = tk.Listbox(root, width=50, height=10)
list_box.pack(pady=20)

# 创建开始和停止按钮
start_button = tk.Button(root, text="开始任务", command=start_task)
start_button.pack(side=tk.LEFT, padx=10)

stop_button = tk.Button(root, text="停止任务", command=stop_task)
stop_button.pack(side=tk.RIGHT, padx=10)

# 使用tkinter变量来控制线程的运行状态
is_running = tk.BooleanVar(value=False)

# 启动主事件循环
root.mainloop()